using System;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;


namespace Agron.Services.SessionController
{
    internal static class NetworkHelper
    {
        private static string _localNetworkIP;

        internal static string LocalNetworkIP
        {
            get
            {
                if (string.IsNullOrEmpty(_localNetworkIP))
                {
                    // Before we strore the value in a static variable, we need to make sure we don't have obsolete data when an network change happens.
                    NetworkChange.NetworkAddressChanged += delegate { _localNetworkIP = string.Empty; };
                    NetworkChange.NetworkAvailabilityChanged += delegate { _localNetworkIP = string.Empty; };

                    IPHostEntry localhost = Dns.GetHostEntry(Environment.MachineName);
                    if (null != localhost)
                    {
                        foreach (IPAddress address in localhost.AddressList)
                        {
                            if (AddressFamily.InterNetwork == address.AddressFamily)
                            {
                                _localNetworkIP = address.ToString();
                                break;
                            }
                        }
                    }
                }

                return _localNetworkIP;
            }
        }
    }
}
